<template>
    <div>
        <div>
            <!-- 面包屑 -->
            <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item :to="{ path: 'home' }">学生互评</el-breadcrumb-item>
                <el-breadcrumb-item>实践互评任务</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <h1 style="border-bottom: 1px solid;padding-bottom: 10px;">学生互评</h1>

        <div class="demo-collapse" style="margin: 3% 5% 3% 5%;">
            <h1>实践互评任务</h1>
            <div style="margin-top:2%;">
                <el-table :data="gitProcessTask" height="200" border stripe style="width: 100%;">
                    <el-table-column prop="courseName" label="实践课程" />
                    <el-table-column prop="processName" label="任务名称" width="180" />
                    <el-table-column prop="processType" label="任务类型" width="180" :formatter="formatTyoe" />
                    <el-table-column prop="adviserName" label="老师" width="180" />
                    <el-table-column prop="scoreStart" label="互评开始日期" :formatter="formatDate" />
                    <el-table-column prop="scoreEnd" label="互评截止日期" :formatter="formatDate" />
                    <el-table-column fixed="right" label="操作" width="120">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="getStuInfo(scope.row.processId)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 打分处 -->
            <el-collapse v-model="activeName" accordion v-if="stuInfo != null">
                <div v-for="(item, index) in stuInfo" :key="index" style="margin-top: 1%;">
                    <el-collapse-item :title="item.appraiseePhone" :name="index" style=" border-bottom: 1px solid #DCDFE6;">
                        <!-- <el-divider /> -->
                        <el-row class="row-bg" justify="center" style="background-color: #FAFAFA;">
                            <el-col :span="6">
                                <div style="margin-top: 4%;">
                                    <el-text tag="b">学生报告：</el-text>
                                    <el-button type="primary" link
                                        @click="downReport(item.appraiseePhone, item.processId,item.filePath)">下载报告</el-button>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div style="display: flex; justify-content: center;text-align: center; left: 20px;">
                                    <el-text tag="b" style="width:100px">请打分：</el-text>

                                    <!-- <el-input v-model="score" placeholder="最终报告分数" clearable
                                        style="width: 50%; height: 50px;" />
                                    <el-button type="info" style="width: 70px; height: 50px;"
                                        @click="scoring(item.processId, item.appraiseePhone)">打分</el-button> -->

                                    <el-form :model="form" :rules="rules" style="margin-top: 5%;">
                                        <el-form-item>
                                            <!-- <el-input v-model="score" placeholder="最终报告分数" clearable
                                            style="width: 50%; height: 50px;" /> -->


                                                <el-input-number :controls="false" v-model="score" class="mx-4"
                                                :min="0" :max="100" controls-position="right" @change="handleChange" 
                                                style="width: 50%; height: 50px;" />

                                            <el-button type="info" style="width: 70px; height: 50px;"
                                                @click="scoring(item.processId, item.appraiseePhone)">打分</el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                            </el-col>
                        </el-row>
                    </el-collapse-item>
                </div>
            </el-collapse>

            <!-- 提示选择任务 -->
            <div v-if="stuInfo.length == null" style="background-color: #F5F7FA;">
                <h1
                    style="font-size: 32px; font-weight: bold; margin-top: 3%; text-align: center; background-color: #F5F7FA;">
                    请先选择互评任务</h1>
            </div>
            <!-- 提醒 -->
            <div
                style="margin-top: 2%; height: 270px; width: auto; border-style:dashed;border-width: 0.1px;border-color: gray;border-radius:10px;">
                <p style="text-indent: 2em; color: #545c64; size: 3px;">
                    1.希望同学们认真进行互评打分任务，在规定的时间要求内，完成相互之间的互评环节。互评是实践中不可缺少的环节，
                    未按要求完成互评的同学最终成绩将受到影响。
                </p>
                <p style="text-indent: 2em; color: #545c64; size: 3px;">2.希望同学们在互评的过程中，严格遵守实践过程管理要求，不出现以下行为：</p>
                <p style="text-indent: 4em; color: #545c64; size: 3px;">·请按照实际情况公平打分，禁止恶性打分行为；</p>
                <p style="text-indent: 4em; color: #545c64; size: 3px;"> ·禁止过高或过低打分行为；</p>
                <p style="text-indent: 4em; color: #545c64; size: 3px;"> ·不要因为是给同学打分而故意虚高分数；</p>
                <p style="text-indent: 4em; color: #545c64; size: 3px;">·禁止重复打分</p>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import * as XLSX from "xlsx"
import requests from '@/api/ajax.js'
import { useRouter } from 'vue-router'
import { saveAs } from 'file-saver';
import { ElMain, ElMessage, ElSubMenu } from 'element-plus';

const router = useRouter()

onBeforeMount(() => {

    const getTask = requests({ url: "/score/processTask", method: "get" }).then(res => {
        if (res.code === 20041) {
            gitProcessTask.value = res.rdata
        } else {
            gitProcessTask.value = null
        }
    })
        .catch(err => {
            console.error(err.data);
            // 登录请求失败后的操作
        });


})

const gitProcessTask = ref([
    // {
    //     processId: '',
    //     processName: "",
    //     processType: '',
    //     startDate: "",
    //     endDate: "",
    //     content: '',
    //     scoreStart:'' ,
    //     scoreEnd: '',
    //     practicalId: '',
    //     classId: '',
    //     className: "",
    //     adviserId: '',
    //     adviserName: "",
    //     teachId: '',
    //     teachName: "",
    //     practicalType: '',
    //     onloadDate: "",
    //     planId: '',
    //     courseId: '',
    //     courseName: "",
    //     majorName: "",
    //     enrolDate: ""
    // }
])

const activeName = ref('1')


//文件预览
/* requests.get('/xlsx', {
    responseType: "arraybuffer", // 设置响应体类型为arraybuffer
}).then(({ data }) => {
    let workbook = XLSX.read(new Uint8Array(data), { type: "array" }); // 解析数据
    var worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
    this.tableau = XLSX.utils.sheet_to_html(worksheet); // 渲染
}) */

function ticketFaceView() {
    requests({
        url: "/xxxxxx/xxxxx/xxxxx", // 接口地址
        method: "get",
        responseType: "blob", // 需要加上
        params: { // 接口需要的参数，视个人情况而定
            ticketBizId: this.ViewData.ticketId,
            packageNo: this.ViewData.superInfoList[0].packageNo,
            ticketRange: this.ViewData.superInfoList[0].ticketRange
        },
    }).then((res) => {
        const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
        );
        // 跳转页面预览
        window.open(pdfFile);
        URL.revokeObjectURL(pdfFile); //释放URL对象
    });
}

//下载报告
function downReport(appraiseePhone, processId,filePath) {

    if(filePath != null){
        const getReport = requests({ url: "/preview/processTask/" + appraiseePhone + "/" + processId, method: "get", responseType: 'blob', }).then(res => {
        // const blob = new Blob([res.rdata], { type: res.rdata.type });
        // saveAs(blob, 'example.docx');

        // 将响应数据转换为 Blob 对象
        const blob = new Blob([res]);
        // 创建链接进行下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = filePath;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

    })
        .catch(err => {
            console.error(err);
            // 登录请求失败后的操作
        });
    }else{
        alert('该学生未提交报告')
    }

    
}

//分数
const score = ref('')

//打分点击事件
function scoring(processId, appraiseePhone) {

    const getScore = requests({ url: "/score/stuGetMouse/" + processId + "/" + appraiseePhone + "/" + score.value, method: "get" }).then(res => {
        if (res.code === 20041) {
            ElMessage.success(res.msg)
        }else if(res.code === 20040){
            ElMessage.warning(res.msg)
        }else{
            ElMessage.warning('发生错误')
            
        }
    })
        .catch(err => {
            console.error(err);
            // 登录请求失败后的操作
        });
}

const stuInfo = ref([
    //     {
    //         stuName: '王二',
    //         files: ''
    //     },
    //     {
    //         stuName: '王三',
    //         files: ''
    //     },
    //     {
    //         stuName: '李四',
    //         files: ''
    //     },
])

//获取需要批改的学生的信息
function getStuInfo(processId) {

    const getTask = requests({ url: "/score/stuGetMouse/" + processId, method: "get" }).then(res => {
        if (res.code === 20041) {
            stuInfo.value = res.rdata
        } else {
            alert(res.msg)
            stuInfo.value = null
        }
    })
        .catch(err => {
            console.error(err.data);
            // 登录请求失败后的操作
        });
}


//时间格式化
function formatDate(row, column, cellValue, index) {
    let format = 'YYYY-mm-dd'
    let date = new Date(cellValue);
    const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
    }
    Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
            format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
    });
    /*  dateFilters.value = format */
    //时间选择栏
    /*  let dateFilters = ref([])
     dateFilters = format */
    // for(let i=0 ; i<myPublish.length;i++){
    //   const obj = ref([])
    //   obj.text = 
    /*   myPublish.value.courseDate = ref(format);
      console.log(myPublish.value.courseDate) */
    return format
}

//将任务类型转换为过程任务或最终任务
function formatTyoe(row, column, cellValue, index) {
    let format = ''
    let date = cellValue;
    if (date === 0) {
        format = '过程任务';
    } else if (date === 1) {
        format = '最终任务';
    }
    return format;
}

// 添加校验规则
const rules = ref([
    { required: true, message: '请填写分数', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '请输入0-100的分数', trigger: 'blur' }
])
</script>

<style></style>